/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.client.dialog.schema.view;

import java.util.HashMap;
import javax.jcr.RepositoryException;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import offset.nodes.client.model.SimpleNamespaceRegistry;
import offset.nodes.client.virtual.model.jcr.QName;

/**
 *
 * @author Walter Lütgenau
 */
public class QNameLabel extends JLabel {
    static HashMap<String,ImageIcon> namespaceIcons = null;

    String prefix;
    String localName;

    public QNameLabel(String prefix, String localName) throws RepositoryException {
        this.prefix = prefix;
        this.localName = localName;

        init();
    }
    
    public QNameLabel(QName qName) throws RepositoryException {
        String prefixName = SimpleNamespaceRegistry.getInstance().toPrefixName(qName);
        String[] names = prefixName.split(":");

        this.prefix = names[0];
        this.localName = names[1];

        init();
    }

    protected void init() throws RepositoryException {
        setIcon(getNamespaceIcon(prefix));
        setToolTipText(prefix + ":" + localName);
    }

    protected ImageIcon getNamespaceIcon(String prefix) throws RepositoryException {
        if (namespaceIcons == null) {
            synchronized(QNameLabel.class) {
                namespaceIcons = new HashMap<String,ImageIcon>();
                for (String namespace : SimpleNamespaceRegistry.getInstance().getPrefixes())
                    namespaceIcons.put(namespace, new ImageIcon(QNameLabel.class.getResource("/offset/nodes/client/view/resources/" + namespace + "Namespace.png")));
            }
        }

        return namespaceIcons.get(prefix);
    }

}
